<?php
namespace app\admin\controller;

use app\admin\model\RoleModel;
use app\admin\model\UserModel;
use app\admin\model\WebsetModel;
use think\Controller;
use org\Verify;
use think\Db;

class Login extends Controller
{
    // 登录页面
    public function index()
    {
		$webset = new WebsetModel();
        $websetInfo = $webset->getInfo();
        DB::name('log')->where('c_time','<',strtotime('-' . $websetInfo['log_expire'] . ' day'))->delete();
		$this->assign([
			'Webset'=>$websetInfo,
            'user_id'=>session('id')
		]);
        return $this->fetch('/login');
    }

    // 登录操作
    public function doLogin()
    {
        $userName = input("param.user_name");
        $password = input("param.password");
        $code = input("param.code");
        $result = $this->validate(compact('userName', 'password', "code"), 'AdminValidate');
        if(true !== $result){
            return json(msg(-1, '', $result));
        }
        $verify = new Verify();
        if (!$verify->check($code)) {
            return json(msg(-2, '', '验证码错误'));
        }
        $userModel = new UserModel();
        $hasUser = $userModel->findUserByName($userName);
        if(empty($hasUser)){
            return json(msg(-3, '', '管理员不存在'));
        }
        if(md5($password . config('salt')) != $hasUser['password']){
            return json(msg(-4, '', '密码错误'));
        }
        if(1 != $hasUser['status']){
            return json(msg(-5, '', '该账号被禁用'));
        }
		// if(!$this->checkPlatform($hasUser)){
		// 	return json(msg(-5, '', '该账号未被平台授权'));
		// }
        // 获取该管理员的角色信息
        $roleModel = new RoleModel();
        $info = $roleModel->getRoleInfo($hasUser['role_id']);
        session('username', $userName);
        session('id', $hasUser['id']);
        session('head', $hasUser['head']);
        session('role', $info['role_name']);  // 角色名
        session('rule', $info['rule']);  // 角色节点
        session('action', $info['action']);  // 角色权限
        if($info['can_see_type'] == 0){//可视权限
            session('can_see',[0=>['create_uid' => $hasUser['id']]]);
        }elseif($info['can_see_type'] == 1 || $info['can_see_type'] == 2){
            $can_see = explode(',',$info['can_see']);
            foreach($can_see as $k => $v){
                $arr[$k] = ['create_uid'=>$v];
            }
            session('can_see',$arr);
        }else{
            session('can_see',[0=>'']);
        }
        // 更新管理员状态
        $param = [
            'login_times' => $hasUser['login_times'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time()
        ];
        $res = $userModel->updateStatus($param, $hasUser['id']);
        if(1 != $res['code']){
            return json(msg(-6, '', $res['msg']));
        }
        return json(msg(1, url('index/index'), '登录成功'));
    }

	public function autologin() {
		$userName = base64_decode(input("user_name"));
        $code = input("param.code");
        $userModel = new UserModel();
        $hasUser = $userModel->findUserByName($userName);
        if(empty($hasUser)){
            $this->error("该用户不存在");
        }
        if(1 != $hasUser['status']){
			$this->error("该账号被禁用");
        }
		if(!$this->checkPlatform($hasUser)){
			$this->error("该账号未被平台授权");
		}
        // 获取该管理员的角色信息
        $roleModel = new RoleModel();
        $info = $roleModel->getRoleInfo($hasUser['role_id']);
        session('username', $userName);
        session('id', $hasUser['id']);
        session('head', $hasUser['head']);
        session('role', $info['role_name']);  // 角色名
        session('rule', $info['rule']);  // 角色节点
        session('action', $info['action']);  // 角色权限
        if($info['can_see_type'] == 0){//可视权限
            session('can_see',[0=>['create_uid' => $hasUser['id']]]);
        }elseif($info['can_see_type'] == 1 || $info['can_see_type'] == 2){
            $can_see = explode(',',$info['can_see']);
            foreach($can_see as $k => $v){
                $arr[$k] = ['create_uid'=>$v];
            }
            session('can_see',$arr);
        }else{
            session('can_see',[0=>'']);
        }
        // 更新管理员状态
        $param = [
            'login_times' => $hasUser['login_times'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time()
        ];
        $res = $userModel->updateStatus($param, $hasUser['id']);
        if(1 != $res['code']){
            return json(msg(-6, '', $res['msg']));
        }
		$this->success('登录成功',url('index/index'));
	}

    // 验证码
    public function checkVerify()
    {
		$fontttfArr = [2,4,6];
		$fontttf = $fontttfArr[array_rand($fontttfArr,1)].".ttf";
        $verify = new Verify();
        $verify->imageH = 32;
        $verify->imageW = 100;
        $verify->length = 4;
        $verify->useNoise = false;
		$verify->useCurve = true;
		$verify->fontttf = $fontttf;
        $verify->fontSize = 14;
        return $verify->entry();
    }

    // 退出操作
    public function loginOut()
    {
        session('username', null);
        session('id', null);
        session('head', null);
        session('role', null);  // 角色名
        session('rule', null);  // 角色节点
        session('action', null);  // 角色权限

        $this->redirect(url('index'));
    }

	/**
	 * [验证平台授权]
	 */
	public function checkPlatform($hasUser) {
		$APPID = 7;
		$roleModel = new RoleModel();
        $role = $roleModel->getRoleInfo($hasUser['role_id']);
		$platform = Db::connect([
			'type'           => 'mysql',
			'hostname'       => '211.149.220.23',
			'database'       => 'ggzq',
			'username'       => 'root',
			'password'       => 'root',
			'hostport'       => '3306',
			'charset'        => 'utf8',
		])->table('system_auth')->where('id',$role['platform_role_id'])->value('app_auth');
		$platform = explode(",",$platform);
		if(in_array($APPID,$platform)){
			return true;
		}else{
			return false;
		}
	}
}
